package com.kpi.processflow.record;


/**
 * @author Kevin Liu
 * @date 2020/5/3 6:53 下午
 */
public final class Profiler {
    private static final ThreadLocal<StageStack> STAGE_RECORDER = new ThreadLocal<>();

    public Profiler() {
    }

    public static void record(String message) {
        StageStack stageStack =  STAGE_RECORDER.get();
        Stage stage;
        if (null == stageStack) {
            stageStack = new StageStack();
            stage = new Stage(message);
            stageStack.push(stage);
            STAGE_RECORDER.set(stageStack);
        } else {
            stage = new Stage(message);
            stageStack.push(stage);
        }

    }

    public static void release() {
        StageStack stageStack = (StageStack) STAGE_RECORDER.get();
        if (null != stageStack) {
            stageStack.release();
        }
    }

    public static void releaseAll() {
        StageStack stageStack = (StageStack) STAGE_RECORDER.get();
        if (null != stageStack) {
            stageStack.releaseAll();
        }
    }

    public static void reset() {
        releaseAll();
        STAGE_RECORDER.remove();
    }

    public static String dump() {
        return dump(true);
    }

    public static String dump(boolean allDump) {
        StageStack stageStack = (StageStack) STAGE_RECORDER.get();
        return null == stageStack ? "{UNRECORDED}" : stageStack.dump(allDump);
    }
}
